package com.thduan.hotfix;

import android.app.Application;
import android.content.Context;
import android.support.multidex.MultiDexApplication;

import com.taobao.sophix.PatchStatus;
import com.taobao.sophix.SophixManager;
import com.taobao.sophix.listener.PatchLoadStatusListener;

/**
 * Created by duantianhui on 2018/9/30.
 */

public class App extends MultiDexApplication{

    public interface MsgDisplayListener {
        void handle(String msg);
    }

    public static MsgDisplayListener msgDisplayListener = null;
    public static StringBuilder cacheMsg = new StringBuilder();

    @Override
    public void onCreate() {
        super.onCreate();
        //检测更新热修复不定
//        SophixManager.getInstance().queryAndLoadNewPatch();     //请求有无最新补丁
    }

    /**
     * 先走 attachBaseContext，再走onCreate
     * @param base
     */
    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        initHotfix();
        Util.logTest();
    }

    private void initHotfix() {
        String appVersion;
        try {
            appVersion = this.getPackageManager().getPackageInfo(this.getPackageName(), 0).versionName;
        } catch (Exception e) {
            appVersion = "1.0.0";
        }

        SophixManager.getInstance().setContext(this)
                .setAppVersion(appVersion)
                .setAesKey(null)
                //.setAesKey("0123456789123456")
                .setEnableDebug(true)
                .setPatchLoadStatusStub(new PatchLoadStatusListener() {
                    @Override
                    public void onLoad(final int mode, final int code, final String info, final int handlePatchVersion) {
                        String msg = new StringBuilder("").append("Mode:").append(mode)
                                .append(" Code:").append(code)
                                .append(" Info:").append(info)
                                .append(" HandlePatchVersion:").append(handlePatchVersion).toString();
                        Util.log("补丁信息：" + msg);
//                        if (msgDisplayListener != null) {
//                            msgDisplayListener.handle(msg);
//                        } else {
//                            cacheMsg.append("\n").append(msg);
//                        }
                    }
                }).initialize();
    }
}
